package com.linkoog.devtools.raw_index;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorUtils {


    public static ThreadPoolExecutor createThreadPoolExecutor(int capacity, int maxTryNum) {
        // 简单的重新入队策略
        RejectedExecutionHandler handler = (r, executor) -> {
            if (!executor.isShutdown()) {
                try {
                    // 等待一段时间后重新提交任务
                    System.out.println("任务 " + r.toString() + " 被拒绝，准备重新提交");
                    Thread.sleep(80); // 等待
                    executor.getQueue().put(r); // 重新提交任务到队列
                } catch (InterruptedException e) {
                    // 如果等待被中断，则不再重新提交
                    Thread.currentThread().interrupt();
                }
            }
        };

        //// 包含重试次数的重新入队策略
        RejectedExecutionHandler retryHandler = (r, executor) -> {
            ConcurrentHashMap<Runnable, AtomicInteger> map = new ConcurrentHashMap<>();
            if (!executor.isShutdown()) {
                AtomicInteger count = map.computeIfAbsent(r, k -> new AtomicInteger(0));
                int tryCount = count.incrementAndGet();
                if (tryCount <= maxTryNum) {
                    try {
                        System.out.println("任务 " + r + " 被拒绝，第 " + tryCount + " 次重试");
                        Thread.sleep(80); // 等待
                        executor.getQueue().put(r); // 重新提交任务到队列
                    } catch (InterruptedException e) {
                        // 如果等待被中断，则不再重新提交
                        Thread.currentThread().interrupt();
                    }
                } else {
                    System.out.println("任务 " + r.toString() + " 达到最大重试次数 " + maxTryNum + "，放弃该任务");
                    // 可以选择抛出异常、记录日志或其他处理方式...
                }
            }
        };


        LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(capacity);
        ThreadPoolExecutor executor = new java.util.concurrent.ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() * 5, // 核心线程数
                Runtime.getRuntime().availableProcessors() * 5,  // 最大线程数
                60,
                TimeUnit.SECONDS,
                queue,   // 阻塞队列
                r -> {   // 线程工厂
                    AtomicInteger threadNumber = new AtomicInteger(1);
                    Thread thread = new Thread(r);
                    thread.setName("Thread-" + threadNumber.getAndIncrement());
                    //thread.setDaemon(false); // 设置为非守护线程，以避免程序退出时中断任务
                    return thread;
                },
                retryHandler
        );

        return executor;
    }


}
